package com.whut.mobilesafe.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.utils.PrefUtils;
import com.whut.mobilesafe.viewholder.GridItemHomeHolder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 作    者：yubo.xiaoyubo
 * 时    间：2015/12/20  10:44.
 * 版    本：1.0
 * 描    述：主界面Activity
 */
public class HomeActivity extends Activity {

    private GridView glRoot;
    private RelativeLayout rlRoot;

    //输入密码和设置密码dialog的控件
    private EditText etPwd;
    private EditText etConfirmPwd;
    private Button btnConfirm;
    private Button btnCancel;

    private MyAdapter mAdapter;

    //9宫格内的内容
    private String[] mHomeNames = new String[]{"手机防盗", "通讯卫士", "软件管理",
            "进程管理", "流量统计", "手机杀毒", "缓存清理", "高级工具", "设置中心"};
    //9宫格对应的图标
    private int[] mImageIds = new int[]{R.mipmap.home_safe,
            R.mipmap.home_callmsgsafe, R.mipmap.home_apps,
            R.mipmap.home_taskmanager, R.mipmap.home_netmanager,
            R.mipmap.home_trojan, R.mipmap.home_sysoptimize,
            R.mipmap.home_tools, R.mipmap.home_settings};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        glRoot = (GridView) findViewById(R.id.gv_root);

        rlRoot = (RelativeLayout) findViewById(R.id.rl_root);


        mAdapter = new MyAdapter();
        glRoot.setAdapter(mAdapter);

        //给9宫格设置点击事件
        glRoot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    // 手机防盗 被点击
                    case 0:
                        showSafeDialog();
                        break;
                    case 1:
                        startActivity(new Intent(getApplicationContext(),BlackListActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(getApplicationContext(),SoftwareAdminActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(getApplicationContext(),ProcessManageActivity.class));
                        break;
                    case 4:
                        startActivity(new Intent(getApplicationContext(),TrafficActivity.class));
                        break;
                    case 5:
                        startActivity(new Intent(getApplicationContext(),AntiVirtusActivity.class));
                        break;
                    case 6:
                        startActivity(new Intent(getApplicationContext(),CacheActivity.class));
                        break;
                    case 7:
                        break;
                    //点击设置中心
                    case 8:
                        Intent intent = new Intent(getApplicationContext(),SettingActivity.class);
                        startActivity(intent);
                        break;
                }
            }


        });

        copyDB("antivirus.db");
    }

    //判断是否是第一次进入手机防盗，如过是就显示设置页面，如果不是就显示主页面
    private void showSafeDialog() {
        String pwd = PrefUtils.getString(this, "pwd");
        if (!TextUtils.isEmpty(pwd)) {
            //弹出输入密码的界面
            showInputPwdDialog();
        } else {
            //弹出设置密码的界面
            showSetPwdDialog();
        }
    }


    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mHomeNames.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GridItemHomeHolder mHolder = null;
            if (convertView == null) {
                mHolder = new GridItemHomeHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.grid_item_home, null);

                mHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                mHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);

                convertView.setTag(mHolder);
            } else {
                mHolder = (GridItemHomeHolder) convertView.getTag();
            }

            mHolder.tvName.setText(mHomeNames[position]);
            mHolder.ivIcon.setImageResource(mImageIds[position]);

            return convertView;
        }
    }


    //弹出设置密码的界面
    private void showSetPwdDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.show_pwd_dialog, null);
        dialog.setView(view);

        etPwd = (EditText) view.findViewById(R.id.et_pwd);
        etConfirmPwd = (EditText) view.findViewById(R.id.et_confirm_pwd);
        btnConfirm = (Button) view.findViewById(R.id.btn_confirm);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pwd = etPwd.getText().toString();
                if (!TextUtils.isEmpty(pwd)) {
                    String confirmPwd = etConfirmPwd.getText().toString();
                    if (!TextUtils.isEmpty(confirmPwd)) {
                        if (pwd.equals(confirmPwd)) {
                            PrefUtils.setString(getApplicationContext(), "pwd", pwd);
                            dialog.dismiss();
                            Intent intent = new Intent(getApplicationContext(), Step1Activity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(getApplicationContext(), "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Toast.makeText(getApplicationContext(), "请您输入确认密码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "请您先输入密码", Toast.LENGTH_SHORT).show();
                }

            }
        });


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    /**
     * 弹出输入密码的界面
     */
    private void showInputPwdDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.show_input_dialog, null);
        dialog.setView(view);


        etPwd = (EditText) view.findViewById(R.id.et_pwd);
        btnConfirm = (Button) view.findViewById(R.id.btn_confirm);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pwd = etPwd.getText().toString();
                String pwdServer = PrefUtils.getString(getApplicationContext(), "pwd");
                if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(pwdServer)) {
                    if (pwd.equals(pwdServer)) {
                        dialog.dismiss();
                        Intent intent = new Intent(getApplicationContext(), LostAndFoundActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(getApplicationContext(), "密码输入错误", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getApplicationContext(), "请您先输入密码", Toast.LENGTH_SHORT).show();
                }

            }
        });


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public void copyDB(String dbName){
        AssetManager assets = getAssets();
        InputStream is =null;
        try {
            //  /data/data/com.whut.mobilesafe/files
            File file = getFilesDir();
            File targetFile = new File(file,dbName);
            if(targetFile.exists()){
                Log.d("HomeActivity", dbName + " 数据库已经存在！无需拷贝");
                return;
            }
            FileOutputStream fos = new FileOutputStream(targetFile);
            is = assets.open(dbName);
            int len = 0;
            byte[] data = new byte[1024];
            while((len=is.read(data))!=-1){
                fos.write(data,0,len);
            }
            is.close();
            fos.close();

            Log.d("HomeActivity", " 数据库 "+dbName + " 拷贝成功！！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
